<template>
  <n-upload
      :directory-dnd="true"
      :action="url"
      :name="name"
      style="width: 100px"
      :max="1"
      list-type="image-card"
      @remove="handleRemove"
      @finish="handleFinish">

    <n-tooltip v-if="curImage" trigger="hover">
      <template #trigger>
        <RemoteImage  :src="curImage" :size="30"></RemoteImage>
      </template>封面
    </n-tooltip>

    <n-upload-dragger v-else>
      <TextIcon icon="material-symbols:archive-outline-sharp" :text="placeholder" :size="16"></TextIcon>
    </n-upload-dragger>


  </n-upload>

</template>

<script setup lang="ts">
import {computed} from "vue";
import { uploadImage} from '~/settings'
import {UploadFileInfo} from "naive-ui";
import TextIcon from "@/components/pc/icon/TextIcon.vue";
import RemoteImage from "@/components/common/image/RemoteImage.vue";

const url = uploadImage.url
const name = uploadImage.name

const props = defineProps({
  image: {
    type: String,
    default: '',
  },
  placeholder: {
    type: String,
    default: '点击或者拖动文件到该区域上传'
  }
})
const emits = defineEmits(['update:image'])
const curImage = computed({
  get: () => {
    return props.image
  },
  set: (val) => {
    emits('update:image', val)
  }
})
const handleRemove = () => {
  curImage.value = ''
}
const handleFinish = ({file, event}: {
  file: UploadFileInfo
  event?: ProgressEvent
}) => {
  const res = JSON.parse((event?.target as XMLHttpRequest).response)
  file.name = res.data
  file.url = file.name
  curImage.value = file.name
  window.$message.success(`图片上传成功，访问路径：` + file.url)
  return file
}
</script>

<style scoped>
:deep(.n-upload-file-list.n-upload-file-list--grid) {
  display: block;
}

:deep(.n-upload-trigger.n-upload-trigger--image-card) {
  width: 100%;
  height: 100%;
}

:deep(.n-upload-file-list .n-upload-file.n-upload-file--image-card-type ) {

  height: 20px;
}
</style>